# -*- coding: utf-8 -*-

import mod.client.extraClientApi as clientApi
from gemstoneScripts.config.sys import *
from gemstoneScripts.config.gemstonePlatform import *

ScreenNode = clientApi.GetScreenNodeCls()
ViewBinder = clientApi.GetViewBinderCls()
ViewRequest = clientApi.GetViewViewRequestCls()


class Main(ScreenNode):
    def __init__(self, namespace, name, param):
        ScreenNode.__init__(self, namespace, name, param)
        self.system = param['system']  # type: ClientSystem
        self.player_id = param['playerId']  # type: str
        self.timer = 0
        self.select_slot = NONE
        self.input = param['input']
        self.output = param['output']
        self.water = param['water']
        self.progress = param['progress']
        self.pos = param['pos']
        self.dim = param['dim']
        pass

    def Create(self):
        self.get_player_bag()
        self.get_ui_data()
        pass

    def Update(self):
        self.timer += 1
        if self.timer >= 3:
            self.get_player_bag()
            self.get_ui_data()
            self.timer = 0
        pass

    @ViewBinder.binding(ViewBinder.BF_ButtonClickUp, '#on_close')
    def on_close(self, args):
        clientApi.PopScreen()
        return ViewRequest.Refresh

    @ViewBinder.binding(ViewBinder.BF_ButtonClickUp, '#on_input')
    def on_click_input(self, args):
        if self.select_slot == NONE:
            self.select_slot = INPUT
            self.set_select_frame(self.select_slot, True)
        else:
            self.set_select_frame(self.select_slot, False)
            if self.select_slot != INPUT:
                self.swap_to_input(self.select_slot)
            self.select_slot = NONE
        pass

    @ViewBinder.binding(ViewBinder.BF_ButtonClickUp, '#on_output')
    def on_click_output(self, args):
        if self.select_slot != NONE:
            self.set_select_frame(self.select_slot, False)
            self.select_slot = NONE
        if self.output:
            self.get_output()
        pass

    @ViewBinder.binding(ViewBinder.BF_ButtonClickUp, '#on_click')
    def on_click_bag(self, args):
        index = args['#collection_index']
        if self.select_slot == NONE:
            self.select_slot = index
            self.set_select_frame(index, True)
        else:
            self.set_select_frame(self.select_slot, False)
            if self.select_slot == INPUT:
                self.swap_to_input(index)
            else:
                self.swap_item(self.select_slot, index)
            self.select_slot = NONE
        pass

    def get_output(self):
        self.system.NotifyToServer(GEMSTONE_PLATFORM_GET_OUTPUT_EVENT,
                                   {'playerId': self.player_id,
                                    'output': self.output,
                                    'pos': self.pos,
                                    'dim': self.dim})
        pass

    def swap_to_input(self, slot):
        self.system.NotifyToServer(GEMSTONE_PLATFORM_SWAP_TO_INPUT,
                                   {'input': self.input,
                                    'slot': slot,
                                    'pos': self.pos,
                                    'dim': self.dim,
                                    'playerId': self.player_id})
        pass

    def swap_item(self, slot1, slot2):
        self.system.NotifyToServer(SWAP_BAG_ITEM_EVENT,
                                   {'playerId': self.player_id,
                                    'item': slot1,
                                    'swapItem': slot2})
        pass

    def set_select_frame(self, slot, visible):
        player_bag = self.GetChildrenName('/background_image/player_bag')
        if slot == INPUT:
            select_frame = self.GetBaseUIControl('/background_image/input/select_frame')
            select_frame.SetVisible(visible)
            return
        if slot == OUTPUT:
            select_frame = self.GetBaseUIControl('/background_image/output/select_frame')
            select_frame.SetVisible(visible)
            return
        select_frame = self.GetBaseUIControl('/background_image/player_bag/' + player_bag[slot] + '/select_frame')
        select_frame.SetVisible(visible)
        pass

    def get_player_bag(self):
        """
        向服务段发送请求，获取玩家背包信息。
        """
        self.system.NotifyToServer(GET_PLAYER_BAG_EVENT, {'playerId': self.player_id})
        pass

    def get_ui_data(self):
        self.system.NotifyToServer(GET_GEMSTONE_PLATFORM_UI_DATA_EVENT,
                                   {'playerId': self.player_id,
                                    'pos': self.pos,
                                    'dim': self.dim})
        pass

    def update_bag_data(self, args):
        bag_dic = args['bagData']
        for _ in xrange(36):
            self.set_slot_item(bag_dic[_], _)
        self.UpdateScreen()
        pass

    def update_ui_data(self, args):
        self.input = args['input']
        self.output = args['output']
        self.water = args['water']
        self.progress = args['progress']
        self.set_slot_item(self.input, INPUT)
        self.set_slot_item(self.output, OUTPUT)
        self.update_water_bar()
        self.update_progress()
        self.UpdateScreen()
        pass

    def update_water_bar(self):
        base = self.GetBaseUIControl('/background_image/water_bar')
        if not base:
            return
        control = base.asProgressBar()
        water_progress = float(self.water) / MAX_WATER
        control.SetValue(water_progress)
        pass

    def update_progress(self):
        base = self.GetBaseUIControl('/background_image/progress_bar')
        base_label = self.GetBaseUIControl('/background_image/progress_label')
        if not base:
            return
        if not base_label:
            return
        control = base.asProgressBar()
        control_label = base_label.asLabel()
        progress = float(self.progress) / MAX_PROGRESS
        control.SetValue(progress)
        control_label.SetText('%.2f %%' % (progress * 100))
        pass

    def set_slot_item(self, item_dic, slot):
        player_bag = self.GetChildrenName('/background_image/player_bag')
        if not player_bag:
            return
        if slot == INPUT:
            base = self.GetBaseUIControl('/background_image/input/item')
            base_count = self.GetBaseUIControl('background_image/input/count')
        elif slot == OUTPUT:
            base = self.GetBaseUIControl('/background_image/output/item')
            base_count = self.GetBaseUIControl('background_image/output/count')
        else:
            base = self.GetBaseUIControl('/background_image/player_bag/' + player_bag[slot] + '/item')
            base_count = self.GetBaseUIControl('/background_image/player_bag/' + player_bag[slot] + '/count')
        if not base_count:
            return
        if not base:
            return
        control_count = base_count.asLabel()
        control = base.asItemRenderer()
        enchant = False
        if item_dic:
            if item_dic['count'] <= 1:
                control_count.SetVisible(False)
            else:
                control_count.SetText(str(item_dic['count']))
                control_count.SetVisible(True)
            if 'enchantData' in item_dic and 'modEnchantData' in item_dic:
                if len(item_dic['enchantData']) > 0 or len(item_dic['modEnchantData']) > 0:
                    enchant = True
            control.SetUiItem(item_dic['newItemName'], item_dic['newAuxValue'], enchant)
            control.SetVisible(True)
            return
        control.SetVisible(False)
        control_count.SetVisible(False)
        pass
